<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="org.dom4j.Document" %>
<%@ page import="org.dom4j.DocumentHelper" %>
<%@ page import="org.dom4j.Element" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.conn.RecordSetDataSource" %>
<%@ page import="weaver.docs.webservices.DocAttachment" %>
<%@ page import="weaver.docs.webservices.DocInfo" %>
<%@ page import="weaver.docs.webservices.DocServiceImpl" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.resource.ResourceComInfo" %>
<%@ page import="weaver.soa.workflow.request.MainTableInfo" %>
<%@ page import="weaver.soa.workflow.request.Property" %>
<%@ page import="weaver.soa.workflow.request.RequestInfo" %>
<%@ page import="weaver.soa.workflow.request.RequestService" %>
<%@ page import="weaver.workflow.request.RequestComInfo" %>
<%@ page import="weaver.workflow.workflow.WorkflowComInfo" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%
    JSONObject jsonData = new JSONObject();
    RecordSetDataSource dataSource = new RecordSetDataSource("zhiyuan");
    String key = Util.null2String( request.getParameter( "key" ) );
    out.print( ">>>>>>开始同步流程>>>>>>>" );
    String formtable = getTableName(key);
    String workflowId ="316";
    String requestName = "法律纠纷申报表";
    String IsNextFlow ="1";
    int secid = 210;
    boolean flag = false;
    try {
        String id = "7311993046710196642";
        String sql = "select start_member_id,start_date,field0001,field0002,field0003,field0004,field0005," +
                "field0006,field0007,field0008,field0009,field0010,field0011 " +
                "from "+formtable+" where id='"+id+"'";
        dataSource.execute(sql);
        while (dataSource.next()){
            Map<String, Object> requestMainMap = new HashMap<String, Object>( );
            String start_member_id = Util.null2String( dataSource.getString( "start_member_id" ) );
            String start_date = Util.null2String( dataSource.getString( "start_date" ) ).substring( 0,19 );
            String username = getUsernameById(start_member_id);
            requestName = requestName+"("+username+" "+start_date+")";
            int creatorId = getUseridByName(username);
            String field0001 = Util.null2String( dataSource.getString( "field0001" ) );
            String field0002 = Util.null2String( dataSource.getString( "field0002" ) );
            String field0003 = Util.null2String( dataSource.getString( "field0003" ) );
            String field0004 = Util.null2String( dataSource.getString( "field0004" ) );
            String field0005 = Util.null2String( dataSource.getString( "field0005" ) );
            String field0006 = Util.null2String( dataSource.getString( "field0006" ) );
            String field0007 = Util.null2String( dataSource.getString( "field0007" ) );
            String field0008 = Util.null2String( dataSource.getString( "field0008" ) );
            String field0009 = Util.null2String( dataSource.getString( "field0009" ) );
            String field0010 = Util.null2String( dataSource.getString( "field0010" ) );
            String field0011 = Util.null2String( dataSource.getString( "field0011" ) );
            String sbbmname = getDepartnameById(field0001);
            int sbbmid = getDepartidByName(sbbmname);
            requestMainMap.put("sbbm",sbbmid);
            String jbrname = getUsernameById(field0002);
            int jbrid = getUseridByName(jbrname);
            requestMainMap.put("jbr",jbrid);
            requestMainMap.put("htmc",field0003);
            requestMainMap.put("htxdf",field0004);
            requestMainMap.put("htje",field0005);
            requestMainMap.put("htbd",field0006);
            requestMainMap.put("jfsm",field0007);
            requestMainMap.put("zflgwyj",field0008);
            requestMainMap.put("szdszps",field0009);
            requestMainMap.put("jsbyj",field0010);
            requestMainMap.put("bmyj",field0011);
            String fileid = getAttachment( id );
            int docid = getDocid(creatorId,secid,fileid);
            requestMainMap.put("fj",docid);
            String requestid = WorkflowCreateByRequestMap(creatorId+"",workflowId,requestName,IsNextFlow,requestMainMap);
            if(Util.getIntValue( requestid,-1 )>0){
                flag = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    jsonData.put( "flag", flag );
    out.print( jsonData.toJSONString() );
    bb.writeLog( "test01=" + jsonData.toJSONString() );
%>
<%!

    public static String getAttachment(String formid){
        BaseBean  baseBean = new BaseBean();
        RecordSetDataSource dataSource = new RecordSetDataSource("zhiyuan");
        dataSource.execute("select id from COL_SUMMARY where form_recordid='"+formid+"'");
        dataSource.next();
        String id = Util.null2String(dataSource.getString( "id" ));
        baseBean.writeLog( ">>>>getAttachment>>>formid="+formid+",id="+id );
        return id;
    }
    //获取文档
    public static int getDocid(int userid,int secid,String fileid){
        BaseBean  baseBean = new BaseBean();
        RecordSetDataSource dataSource = new RecordSetDataSource("zhiyuan");
        User user = new User(userid);
        int docid = -1;
        dataSource.execute("slelect filename,file_url,createdate from CTP_ATTACHMENT where sub_reference='"+fileid+"'");
        if(dataSource.next()){
            String filename = Util.null2String(dataSource.getString( "filename" ));
            String file_url = Util.null2String(dataSource.getString( "file_url" ));
            String createdate = Util.null2String(dataSource.getString( "createdate" ));
            String year = createdate.substring( 0,4 );
            String month = createdate.substring( 5,7 );
            String day = createdate.substring( 8,10 );
            String filepath = "D:\\Seeyon\\A8\\base\\upload\\"+year+"\\"+month+"\\"+day+"\\"+file_url;
             docid = createDoc( user, filename, filepath, secid );
        }
        baseBean.writeLog( ">>>>getDocid>>>userid="+userid+",secid="+secid+",fileid="+fileid+",docid="+docid );
        return docid;
    }
    //根据用户名称获取OA用户ID
    public static int getUseridByName(String name){
        BaseBean  baseBean = new BaseBean();
        RecordSet rs = new RecordSet(  );
        rs.executeQuery("select id from hrmresource where lastname='"+name+"'");
        rs.next();
        int id = Util.getIntValue(rs.getString( "id" ));
        baseBean.writeLog( ">>>>getUseridByName>>>name="+name+",id="+id );
        return id;
    }
    //根据部门名称获取OA部门ID
    public static int getDepartidByName(String name){
        BaseBean  baseBean = new BaseBean();
        RecordSet rs = new RecordSet(  );
        rs.executeQuery("select id from hrmdepartment where departmentname='"+name+"'");
        rs.next();
        int id = Util.getIntValue(rs.getString( "id" ));
        baseBean.writeLog( ">>>>getUseridByName>>>name="+name+",id="+id );
        return id;
    }
    //动态获取致远流程表单
    public static String getTableName(String key){
        BaseBean  baseBean = new BaseBean();
        String formtable ="";
        RecordSetDataSource dataSource = new RecordSetDataSource("zhiyuan");
        try {
            String sql = "select field_info from FORM_DEFINITION where name='"+key+"'";
            dataSource.execute(sql);
            if(dataSource.next()){
                String field_info = Util.null2String( dataSource.getString( "field_info" ) );
                Document xmlDocument = DocumentHelper.parseText(field_info);
                if(xmlDocument!=null) {
                    Element rootElement = xmlDocument.getRootElement();
                    Element table = rootElement.element( "Table" );
                    formtable = table.attributeValue( "name" );
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseBean.writeLog( ">>>>getTableName>>>key="+key+",formtable="+formtable );
        return formtable;
    }
    //获取致远人员部门名称
    public static String getDepartnameById(String departid){
        BaseBean  baseBean = new BaseBean();
        RecordSetDataSource dataSource = new RecordSetDataSource("zhiyuan");
        String sql = "select name from ORG_UNIT where id='"+departid+"'";
        dataSource.execute(sql);
        dataSource.next();
        String departname = Util.null2String( dataSource.getString( "name" ));
        baseBean.writeLog( ">>>>getDepartnameById>>>departid="+departid+",departname="+departname );
        return departname;
    }
    //获取致远人员名称
    public static String getUsernameById(String userid){
        BaseBean  baseBean = new BaseBean();
        RecordSetDataSource dataSource = new RecordSetDataSource("zhiyuan");
        String sql = "select name from ORG_MEMBER where id='"+userid+"'";
        dataSource.execute(sql);
        dataSource.next();
        String username = Util.null2String( dataSource.getString( "name" ));
        baseBean.writeLog( ">>>>getUsernameById>>>userid="+userid+",username="+username );
        return username;
    }
    //创建流程
    public static String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, Object> requestMainMap) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog( "-------WorkflowCreateByRequestMap---------" );
        baseBean.writeLog( ">>>>>creatorId:" + creatorId );
        baseBean.writeLog( ">>>>>workflowId:" + workflowId );
        baseBean.writeLog( ">>>>>requestName:" + requestName );
        baseBean.writeLog( ">>>>>IsNextFlow:" + IsNextFlow );
        RecordSet rs = new RecordSet();
        rs.execute( "select (case when activeVersionID is null then id else activeVersionID end) as wfid   from workflow_base where id=" + workflowId );
        rs.next();
        workflowId = Util.null2String( rs.getString( "wfid" ) );

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid( creatorId );//
        requestInfo.setWorkflowid( workflowId );//
        requestInfo.setDescription( requestName );//
        requestInfo.set_Remark( "" );
        if ("0".equals( IsNextFlow )) {
            requestInfo.setIsNextFlow( IsNextFlow );
        }

        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, Object> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName( Util.null2String( entry.getKey() ) );
            propertyArray[p].setValue( Util.null2String( entry.getValue() ) );
            baseBean.writeLog( ">>>>>>>>p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue() );
            p++;
        }
        baseBean.writeLog( ">>>>>>>>参数个数:" + p );
        mainTableInfo.setProperty( propertyArray );
        requestInfo.setMainTableInfo( mainTableInfo );

        RequestService service = new RequestService();
        try {
            requestid = service.createRequest( requestInfo );
            StringBuffer sbf = new StringBuffer();
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append( ">>>>>>>>>姓名:" + rscif.getLastname( rcif.getRequestCreater( requestid ) ) );
            sbf.append( ">>>>>>>>>时间:" + rcif.getRequestCreateTime( requestid ) );
            sbf.append( ">>>>>>>>>创建流程:" + wfcif.getWorkflowname( workflowId ) );
            sbf.append( ">>>>>>>>>请求:" + rcif.getRequestname( requestid ) );
            sbf.append( ">>>>>>>>>请求:" + requestid );
            sbf.append( ">>>>>>>>>创建工作流记录日志结束" );
            baseBean.writeLog( sbf.toString() );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestid;
    }
    //创建文档
    public static int createDoc(User user, String rawFileName, String path, int secid) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog( ">>>>>>createDocs>>>>>>" );
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocInfo doc = new DocInfo(); //创建文档
        String keyword = ""; //文档内容
        try {
            DocAttachment[] docattachment = new DocAttachment[1];
            baseBean.writeLog( ">>>>>rawFileName=" + rawFileName );
            String filetype = "";
            if (rawFileName.lastIndexOf( "." ) > -1) {
                filetype = rawFileName.substring( rawFileName.lastIndexOf( "." ) + 1 );
            }
            byte[] content = new byte[102400];
            // 上传附件，创建html文档
            content = null;
            try {
                int byteread;
                byte data[] = new byte[1024];
                InputStream input = new FileInputStream( new File( path ) );
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                while ((byteread = input.read( data )) != -1) {
                    outputStream.write( data, 0, byteread );
                    outputStream.flush();
                }
                content = outputStream.toByteArray();
                baseBean.writeLog( ">>>>>content=" + content.length);
                input.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            DocAttachment da = new DocAttachment();
            da.setFilename( rawFileName );//附件标题
            da.setFilecontent( Base64.encode( content ) ); //附件内容
            da.setFiletype( filetype ); //imagefiletype
            da.setImagefilename( rawFileName );// 附件标题
            da.setIszip( 1 );//是否压缩
            da.setIsAesEncrype( 0 );//是否加密
            da.setAesCode( "0" );
            da.setIsextfile( "1" ); //附件是否是office类型

            if (filetype.equalsIgnoreCase( "doc" )) {
                da.setDocfiletype( "3" );
            } else if (filetype.equalsIgnoreCase( "xls" )) {
                da.setDocfiletype( "4" );
            } else if (filetype.equalsIgnoreCase( "ppt" )) {
                da.setDocfiletype( "5" );
            } else if (filetype.equalsIgnoreCase( "wps" )) {
                da.setDocfiletype( "6" );
            } else if (filetype.equalsIgnoreCase( "docx" )) {
                da.setDocfiletype( "7" );
            } else if (filetype.equalsIgnoreCase( "xlsx" )) {
                da.setDocfiletype( "8" );
            } else if (filetype.equalsIgnoreCase( "pptx" )) {
                da.setDocfiletype( "9" );
            } else {
                da.setDocfiletype( "2" );
            }
            docattachment[0]= da;
            keyword = rawFileName;
            doc.setAttachments( docattachment );
            doc.setSeccategory( secid );//子目录id
            doc.setDocSubject( keyword );//标题
            doc.setDoccontent( "" );//文档内容
            /*文档属性*/
            doc.setDocType( 1 );
            //文档状态
            doc.setDocStatus( 1 );
            doc.setDocStatusStr( "正常" );
            //新闻类型
            doc.getDocPublishType();
            doc.setPublishable( "文档" );
            doc.setKeyword( keyword );
            docid = docserviceimpl.createDocByUser( doc, user );
            baseBean.writeLog( ">>>>>docid=" + docid );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docid;
    }
%>